package com.chooseCourses.servlet.admin;

import com.chooseCourses.dao.BaseDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;

@WebServlet("/CourseAdd")
public class CourseAdd extends HttpServlet {
    public CourseAdd() {
        super();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        writer.append("Served at:").append(req.getContextPath());
//        resp.getWriter().append("Served at: ").append(req.getContextPath());
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String room = req.getParameter("room");
        String userName = req.getParameter("userName");
        int userId = Integer.parseInt(req.getParameter("userId"));

        // 创建数据库操作对象
        BaseDao baseDao = new BaseDao();
        PreparedStatement ps=null;// 创建ps对象
        String sql = "insert into course(id,name,room) values(?,?,?)";

        // 调用db中的方法
        // 添加数据
        try {
            ps = baseDao.getConnection().prepareStatement(sql);
            ps.setString(1, id);
            ps.setString(2, name);
            ps.setString(3, room);
            ps.executeUpdate();// 执行sql语句
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                baseDao.closeResource(null,ps,null);// 关闭数据流
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        resp.sendRedirect("admin/courseMes.jsp?userName=" + userName + "&userId=" + userId);
        doGet(req, resp);
    }
}